package com.example.springinitialization.interception;

import com.example.springinitialization.constant.ErrorCode;
import com.example.springinitialization.exception.MyException;
import com.example.springinitialization.utils.token.LoginUserUtils;
import org.springframework.http.HttpRequest;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private HttpRequest httpRequest;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("LoginUser");
        // 如果获取不到 token 或者 token与当前用户不匹配，直接拦截
        if(token == null || token.equals(LoginUserUtils.getToken())) {
            throw new MyException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return true;
    }
}
